package com.ming.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ming.common.CodeMsg;
import com.ming.common.realm.ActiveUser;
import com.ming.common.Constant;
import com.ming.common.Result;
import com.ming.from.SysUserForm;
import com.ming.mapper.SysPermissionMapper;
import com.ming.query.SysUserQuery;
import com.ming.vo.SysPermissionVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ming.mapper.SysUserMapper;
import com.ming.domain.SysUser;
import com.ming.service.SysUserService;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 *@Author:何元才
 *@Desc:
 *@data:2021-04-09 23:15
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    /**
     * 获取当前用户得菜单
     *
     * @return
     */
    @Override
    public Result menu() {
        //当前用户
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = activeUser.getSysUser();
        Integer userId = sysUser.getId();
        //用户所有的权限
        List<SysPermissionVO> sysPermissionVOS = sysPermissionMapper.queryUserPermission(userId);
        //获取所有的菜单权限
        List<SysPermissionVO> menus = sysPermissionVOS.stream().filter(sysPermissionVO -> sysPermissionVO.getType().equals(Constant.PPERMISSION_TYPE_MENU)).collect(Collectors.toList());
        //返回用户的菜单
        List<SysPermissionVO> userMenus = new ArrayList<>();
        for (SysPermissionVO menu : menus) {
            //1级菜单
            if (menu.getParentId().equals(Constant.ROOT_PARENT_ID)){
                //为1级菜单 初始化2级菜单的容器
                List<SysPermissionVO> childs = new ArrayList<>();
                menu.setChildren(childs);
                //放入到菜单中
                userMenus.add(menu);
                //找当前1级菜单的2级菜单
                Integer lv1Id = menu.getId();
                for (SysPermissionVO menu2 : menus) {
                    //获取父菜单的ID
                    Integer menuId = menu2.getParentId();
                    if (menuId.equals(lv1Id)){
                        //放入到2级菜单容器中
                        childs.add(menu2);
                    }
                }
            }
        }
        return new Result(userMenus);
    }

    /**
     * 分页查询用户信息
     *
     * @return
     */
    @Override
    public Result queryPage(SysUserQuery query) {
        Page<SysUser> page = new Page<>(query.getPage(),query.getLimit());
        Page<SysUser> sysUserPage = sysUserMapper.selectPage(page, new LambdaQueryWrapper<SysUser>()
                .like(StringUtils.hasText(query.getRealname()), SysUser::getRealname, query.getRealname())
                .eq(StringUtils.hasText(query.getPhone()), SysUser::getPhone, query.getPhone())
                .eq(!ObjectUtils.isEmpty(query.getSex()), SysUser::getSex, query.getSex())
                .eq(!ObjectUtils.isEmpty(query.getDeleted()), SysUser::getDeleted, query.getDeleted())
                .orderByDesc(SysUser::getCreateTime)
        );
        return new Result(sysUserPage);
    }

    /**
     * 新增用户
     *
     * @param form
     * @return
     */
    @Override
    public Result add(SysUserForm form) {
        // 进行业务数据校验 --> 将数据和数据库进行对比
        // 登录名 或者 手机号 不能重复
        SysUserQuery query = new SysUserQuery();
        // 1.根据登陆名查询
        query.setLoginName(form.getLoginName());
        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getLoginName, query.getLoginName())
        );
        if (user != null) {
            return new Result(CodeMsg.USER_LOGIN_NAME_EXIST_ERROR);
        }
        // 2.校验手机号
        query = new SysUserQuery();
        query.setPhone(form.getPhone());
        user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq( SysUser::getPhone, query.getPhone())
        );
        if (user != null) {
            return new Result(CodeMsg.USER_LOGIN_NAME_EXIST_ERROR);
        }
        //没问题 进行新增
        //创建一个默认密码
        Md5Hash md5Hash = new Md5Hash(Constant.DEFAULT_PASSWORD, Constant.SALT, Constant.COUNT);
        form.setLoginPassword(md5Hash.toString());
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(form,sysUser);
        sysUser.setDeleted(1);
        sysUserMapper.insert(sysUser);
        return new Result();
    }

    /**
     * 根据id 重置密码
     *
     * @param id
     * @return
     */
    @Override
    public Result resetPassword(Integer id) {
        // 根据id 查询用户
        SysUser user = sysUserMapper.selectById(id);
        //用户是无效状态下 返回error
        if (user == null || user.getDeleted().equals(Constant.INVALID)) {
            return new Result(CodeMsg.USER_VALID_ERROR);
        }
        //修改密码 腰产生md5
        String password = new Md5Hash(Constant.DEFAULT_PASSWORD, Constant.SALT, Constant.COUNT).toString();
        user.setLoginPassword(password);
        sysUserMapper.updateById(user);
        return new Result();
    }

    /**
     * 删除用户 逻辑删除
     *
     * @param id
     * @return
     */
    @Override
    public Result deleted(Integer id) {
        // 根据id 查询用户
        SysUser user = sysUserMapper.selectById(id);
        //无效
        if (user == null || user.getDeleted().equals(Constant.INVALID)) {
            return new Result(CodeMsg.USER_VALID_ERROR);
        }
        user.setDeleted(2);
        sysUserMapper.updateById(user);
        return new Result();
    }

    /**
     * 设置用户角色
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    public Result setUserRole(Integer userId, List<Integer> roleIds) {
        //删除用户所有角色
        sysUserMapper.deleteUserRole(userId);
        //新增用户角色关系
        sysUserMapper.batchInsertUserRole(userId, roleIds);
        return new Result();
    }

    /**
     * 修改密码
     *
     * @param id
     * @param newPassword
     * @return
     */
    @Override
    public Result updatePassword(Integer id, String newPassword) {
        // 根据id 查询用户
        SysUser user = sysUserMapper.selectById(id);
        newPassword = new Md5Hash(newPassword, Constant.SALT, Constant.COUNT).toString();
        user.setLoginPassword(newPassword);
        sysUserMapper.updateById(user);
        return new Result();
    }
}
